package site.wanjiahao;

/**
 * 取出最大最小值都可以使用元素第一个作为标志，而不需要使用Integer.MAX 或者Integer.MIN
 */
public class Main {

    public static void main(String[] args) {
        int[] ary = {-2, 1, -3, 4, -1 ,2, 1, -5, 4};
        System.out.println(maxSubAry2(ary));
    }

    // 暴力解法
    static int maxSubAr1(int[] ary) {
        if (ary == null || ary.length == 0) return 0;
        // 定义初始最大子串
        int max = ary[0];
        for (int begin = 0; begin < ary.length; begin++) {
            for (int end = begin; end < ary.length; end++) {
                int sum = 0;
                for (int i = begin; i <= end; i++) {
                    sum += ary[i];
                }
                // 选出最大值
                max = Math.max(max, sum);
            }
        }
        return max;
    }

    // 暴力解法, 优化方案
    static int maxSubAry2(int[] ary) {
        if (ary == null || ary.length == 0) return 0;
        // 定义初始最大子串
        int max = ary[0];
        for (int begin = 0; begin < ary.length; begin++) {
            int sum = 0;
            for (int end = begin; end < ary.length; end++) {
                sum += ary[end];
                // 选出最大值
                max = Math.max(max, sum);
            }
        }
        return max;
    }


    static int maxSubAry(int[] ary) {
        if (ary == null || ary.length == 0) return 0;
        // 左闭右开
        return maxSubAry(ary, 0, ary.length);
    }

    // 分治解法
    static int maxSubAry(int[] ary, int begin, int end) {
        // 递归出口
        if (end - begin < 2) return ary[begin];
        int mid = begin + end >> 1;
        // 再此，序列最大还包括中间那部分
        int leftMax = ary[mid - 1];
        int leftSum = leftMax;
        for (int i = mid - 2; i >= begin ; i--) {
            // 从中间到begin，需要最大值
            leftSum += ary[i];
            leftMax = Math.max(leftMax, leftSum);
        }

        int rightMax = ary[mid];
        int rightSum = rightMax;
        for (int i = mid + 1; i < end ; i++) {
            // 从中间到begin，需要最大值
            rightSum += ary[i];
            rightMax = Math.max(rightMax, rightSum);
        }
        return Math.max(leftMax + rightMax,
                Math.max(maxSubAry(ary, begin, mid), maxSubAry(ary, mid, end)));
    }

}
